<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日报展示</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/static/paper/plugins/element-ui/index.css"/>

    <link rel="stylesheet" href="/static/paper/styles/page.css"/>
    <link rel="stylesheet" href="/static/paper/styles/zgs.css">
    <style>
        .el-table .cell {
            white-space: nowrap; /* 不换行 */
            overflow: hidden; /* 隐藏溢出部分 */
            text-overflow: ellipsis; /* 超出部分用省略号表示 */
        }

        .filter-container {
            display: flex; /* 使用 Flexbox 布局 */
            align-items: center; /* 垂直居中对齐 */
            gap: 20px; /* 元素之间的间距 */
            padding: 1px; /* 内边距 */
        }

        .demonstration {
            font-weight: bold; /* 加粗文本 */
            margin-right: 8px; /* 右边距 */
        }

        .date-picker {
            min-width: 80px; /* 设置日期选择器的最小宽度 */
            max-width: 450px; /* 设置角色选择器的最大宽度 */
            flex-grow: 1; /* 让日期选择器占据更多空间 */
        }

        .role-select {
            min-width: 80px; /* 设置角色选择器的最小宽度 */
            max-width: 100px; /* 设置角色选择器的最大宽度 */
            width: 100%; /* 使其宽度自适应，最大不超过 max-width */
        }

        .search-input {
            min-width: 150px; /* 设置输入框的最小宽度 */
        }

        .zgs-el-button {
            margin-left: 8px; /* 按钮之间的间距 */
        }

    </style>
</head>
<body>
<div class="dashboard-container" id="category-app">
    <div class="container">

        <div class="filter-container">
            <span class="demonstration">日期:</span>
            <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="选择起始日期"
                    end-placeholder="选择结束日期"
                    :picker-options="pickerOptions"
                    class="date-picker"
            ></el-date-picker>
            <span class="demonstration">类型:</span>
            <el-select v-model="roleValue" placeholder="请选择角色" class="role-select">
                <el-option label="所有" value=""></el-option> <!-- 默认选项 -->
                <el-option label="学生" value="1"></el-option>
                <el-option label="职工" value="2"></el-option>
            </el-select>
            <el-input v-model="searchValue" placeholder="查询的人员姓名" class="search-input"></el-input>
            <el-button type="primary" @click="fetchDailyReports" icon="el-icon-search">查询</el-button>
            <el-button slot="reference" @click="confirmExport" type="warning" icon="el-icon-download">导出</el-button>

        </div>

        <!-- 修改后的表格部分 -->
        <el-table
                :data="pageData"
                stripe
                style="width: 100%"
                height="700"
                highlight-current-row=true
                :row-style="{ height: '63px' }">
            <el-table-column
                    fixed
                    label="员工姓名"
                    width="76"
                    align="center">
                <template slot-scope="scope">
                    <el-tooltip class="item" content="查看个人详情" effect="light" placement="top-start">
                        <a :href="'particular.html?em_id=' + encodeURIComponent(scope.row.id)"
                           style="text-decoration: none; color: inherit;">{{ scope.row.name }}</a>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column
                    v-for="date in allDates" :key="date"

                    :width="auto"
                    align="center">
                <template slot="header">
                    <div style="display: flex; flex-direction: column; align-items: center; line-height: 1.2; padding: 0;">
                        <span style="color: rgba(23, 23, 23, 0.7);">{{ headerDate(date) }}</span> <!-- 显示 MM-DD -->
                        <span style="color: rgba(0, 0, 0, 0.3);">({{ headerWeekday(date) }})</span> <!-- 显示对应的星期几 -->
                    </div>
                </template>
                <template slot-scope="scope">
        <span>
            <el-tag
                    v-if="scope.row.daypapers[date] === -1"
                    type="danger"
                    size="mini"
                    class="status-tag">
                <i class="el-icon-error" style="margin-right: 4px;"></i> 未提交
            </el-tag>
            <el-tag
                    v-else-if="scope.row.daypapers[date] === 0"
                    type="info"
                    size="mini"
                    class="status-tag">
                <i class="el-icon-info" style="margin-right: 4px;"></i> 休息
            </el-tag>
            <el-tag
                    v-else-if="scope.row.daypapers[date] === 1"
                    type="success"
                    size="mini"
                    class="status-tag">
                <i class="el-icon-success" style="margin-right: 4px;"></i> 已提交
            </el-tag>
            <el-tag
                    v-else-if="scope.row.daypapers[date] === 2"
                    type="primary"
                    size="mini"
                    class="status-tag">
                <i class="el-icon-info" style="margin-right: 4px;"></i> 请假
            </el-tag>
            <el-tag
                    v-else-if="scope.row.daypapers[date] === 3"
                    type="primary"
                    size="mini"
                    class="status-tag">
                <i class="el-icon-info" style="margin-right: 4px;"></i> 休假
            </el-tag>
            <el-tag
                    v-else
                    type="warning"
                    size="mini"
                    class="status-tag">
            <i class="el-icon-warning" style="margin-right: 4px;"></i> 无数据
            </el-tag>
        </span>
                </template>
            </el-table-column>
        </el-table>

        <div class="block" style="display: flex; justify-content: flex-end;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 400]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalRecords">
            </el-pagination>
        </div>

    </div>
</div>

<script src="/static/paper/plugins/vue/vue.js"></script>
<script src="/static/paper/plugins/element-ui/index.js"></script>
<script src="/static/paper/plugins/axios/axios.min.js"></script>
<script src="/static/paper/js/request.js"></script>

<script>
    new Vue({
        el: '#category-app',
        data() {
            return {
                tableData: [], // 用于存放日报数据
                pageData: [], // 存放当页日报数据(动态)
                allDates: [], // 用于存放所有日期
                searchValue: '', // 搜索框内容
                dateRange: [], // 用于存储选择的日期范围
                roleValue: '', // 角色选择的model
                currentPage: 1,
                pageSize: 10,
                totalRecords: 14,
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            end.setDate(end.getDate() - 1);
                            start.setDate(end.getDate() - 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近两周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            end.setDate(end.getDate() - 1);
                            start.setDate(end.getDate() - 14);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            end.setDate(end.getDate() - 1);
                            start.setDate(end.getDate() - 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            end.setDate(end.getDate() - 1);
                            start.setDate(end.getDate() - 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                }
            }
        },
        methods: {
            fetchDailyReports() {
                // 获取日报数据的逻辑
                const end = new Date();
                end.setDate(end.getDate() - 1); // 结束日期为前一天
                const start = new Date();
                start.setDate(end.getDate() - 7); // 起始日期为前一周

                const sinceDate = this.dateRange && this.dateRange.length > 0 ? new Date(this.dateRange[0]) : start;
                const endDate = this.dateRange && this.dateRange.length > 1 ? new Date(this.dateRange[1]) : end;

                // 计算日期范围差
                const timeDiff = endDate - sinceDate; // 时间差（毫秒）
                const daysDiff = timeDiff / (1000 * 3600 * 24); // 转换为天数

                // 检查日期范围是否超过 30 天
                if (daysDiff > 29) {
                    this.$message.warning({
                        showClose: true,
                        message: '所选日期范围超过了30天，请导出查看'
                    });
                    return; // 结束函数执行
                }

                // 生成 allDates 数组
                this.allDates = [];
                let currentDate = new Date(sinceDate); // 从 sinceDate 开始
                while (currentDate <= endDate) {
                    this.allDates.push(this.formatDate(currentDate));
                    // 增加一天
                    currentDate.setDate(currentDate.getDate() + 1);
                }

                // 调试信息，查看请求参数
                console.log('请求参数:', {
                    today: new Date(),
                    since_date: this.formatDate(sinceDate),
                    end_date: this.formatDate(endDate),
                    employee_names: this.searchValue || "",
                    role: this.roleValue || ""
                });

                fetch('/daypaper/show', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        'since_date': this.formatDate(sinceDate),
                        'end_date': this.formatDate(endDate),
                        'names': this.searchValue || "",
                        'role': this.roleValue || ""
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === "error") {
                            this.$message.error({
                                showClose: true,
                                message: data.msg,
                            });
                            return; // 结束函数执行
                        }
                        this.tableData = data.data.records || []; // 保存所有记录
                        this.totalRecords = this.tableData.length; // 更新总记录数
                        this.updatePagedData(); // 更新分页数据

                        if (this.tableData.length > 0) {
                            console.log("原始数据：", data);
                            if (data.status === "success") {
                                this.$message.success({
                                    showClose: true,
                                    message: data.msg,
                                    duration: 1000
                                });
                            }
                        } else {
                            this.allDates = []; // 如果没有记录，清空日期
                            this.$message.warning({
                                showClose: true,
                                message: "所选时间段没有数据"
                            });
                        }
                    })
                    .catch(error => {
                        console.error('获取数据时出错:', error);
                    });
            },
            confirmExport() {
                this.$confirm("点击确定导出", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    //用户确认导出
                    this.exportToExcel();
                }).catch(() => {
                    //用户取消导出
                    this.$message.warning({
                        showClose: true,
                        message: "已取消导出"
                    })
                })
            },
            exportToExcel() {
                // 导出为 Excel 的逻辑
                const end = new Date();
                const start = new Date();
                end.setDate(end.getDate() - 1);
                start.setDate(end.getDate() - 7);
                const sinceDate = this.formatDate(this.dateRange && this.dateRange.length > 0 ? this.dateRange[0] : start) || this.formatDate(start);
                const endDate = this.formatDate(this.dateRange && this.dateRange.length > 1 ? this.dateRange[1] : end) || this.formatDate(end);
                const employeeNames = this.searchValue || ""; // 获取员工姓名
                const role = this.roleValue || ""; // 获取角色（需要在 data 中定义）

                // 调试信息，查看请求参数
                console.log('请求参数:', {
                    since_date: sinceDate,
                    end_date: endDate,
                    employee_names: employeeNames,
                    role: role
                });

                fetch('/daypaper/output_excel', {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        "since_date": sinceDate,
                        "end_date": endDate,
                        "names": employeeNames,
                        "role": role
                    })
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error("网络响应不是 OK");
                        }
                        return response.blob();  // 将响应转换为 Blob 对象
                    })
                    .then(blob => {
                        // 创建一个链接并下载文件
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'DayPaper.xlsx';  // 设置下载文件名,可以省略
                        document.body.appendChild(a);
                        a.click();
                        a.remove();
                        window.URL.revokeObjectURL(url);  // 释放 URL 对象

                        // 打印导出成功信息
                        this.$message.success({
                            showClose: true,
                            message: "导出成功！"
                        });
                    })
                    .catch(error => {
                        console.error("导出数据错误", error);
                        this.$message.error({
                            showClose: true,
                            message: "导出失败: " + error.message
                        });
                    });
            },
            headerDate(date) {
                // 将日期字符串拆分为数组
                const parts = date.split('-');
                // 返回月份和日期部分
                return `${parts[1]}-${parts[2]}`; // MM-DD 格式
            },
            headerWeekday(date) {
                // 将日期字符串转换为 Date 对象
                const dateObj = new Date(date);
                // 获取星期几的中文表示
                const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                return `周${weekdays[dateObj.getDay()]}`; // 返回对应的星期几
            },
            formatDate(date) {
                if (!date) return ""; // 如果日期为空，返回空字符串
                const d = new Date(date); // 创建新的 Date 对象
                const year = d.getFullYear(); // 获取年份
                const month = String(d.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
                const day = String(d.getDate()).padStart(2, '0'); // 获取日期并补零
                return `${year}-${month}-${day}`; // 返回格式化后的字符串
            },
            updatePagedData() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = this.currentPage * this.pageSize;
                this.pageData = this.tableData.slice(start, end);
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.updatePagedData();
            },
            handleSizeChange(size) {
                this.pageSize = size;
                this.updatePagedData();
            }
        },
        created() {
            this.fetchDailyReports(); // 初始化时获取日报数据
        }
    });
</script>
</body>
</html>
